package com.zwcl.glass.tools.controller;


import com.zwcl.common.core.domain.entity.ApiResult;
import com.zwcl.common.core.enums.ExceptionCode;
import com.zwcl.common.core.exception.BusinessException;
import com.zwcl.common.core.redis.RedisLock;
import com.zwcl.common.core.redis.RedisLockLua;
import com.zwcl.common.core.validator.groups.Add;
import com.zwcl.glass.tools.entity.Article;
import com.zwcl.glass.tools.entity.ArticleCategory;
import com.zwcl.glass.tools.entity.ArticleRead;
import com.zwcl.glass.tools.service.ArticleReadService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author xieyongping
 * @since 2021-01-11
 */
@RestController
@RequestMapping("/articleRead")
public class ArticleReadController {

    @Autowired
    private ArticleReadService articleReadService;

    @Autowired
    private RedisLock redisLock;

    private final String articleReadRedisLockKey="RedisLock:Article:Read:";
    /**
     * 添加
     */
    @PostMapping("/count")
    public ApiResult<Boolean> updateReadCount(@RequestBody ArticleRead articleRead) throws Exception {
        try {
            Boolean flag=true;

            if(redisLock.tryLock(articleReadRedisLockKey+articleRead.getArticleId(),60*1000L)) {
                if (null != articleRead.getId()) {
                    flag = articleReadService.saveArticalReadCount(articleRead);
                } else {
                    ArticleRead dbArticleRead = articleReadService.getArticalReadById(articleRead.getArticleId());
                    if (null != dbArticleRead) {
                        articleRead.setId(dbArticleRead.getId());
                        flag = articleReadService.saveArticalReadCount(articleRead);
                    } else {
                        if (articleRead.getLikeNum() < 0 || articleRead.getReadNum() < 0) {
                            throw new BusinessException("参数数据不能<0");
                        }
                        flag = articleReadService.save(articleRead);
                    }
                }
                return ApiResult.result(flag);
            }else {
                return ApiResult.fail(ExceptionCode.SYSTEM_BUSY,false);
            }
        } finally {
            redisLock.unlock(articleReadRedisLockKey+articleRead.getArticleId());
        }
    }

}

